package com.fanco.learn_datastruct_leetcode.juc;/**
 * @author qiaowang 2021/8/17
 */

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author fanco
 * @Desc 描述
 */
public class ContainerNotSafeDemo {
    public static void main(String[] args) {
        listNotSafe();
        setNotSafe();
        mapNotSafe();
    }

    private static void mapNotSafe() {
//        Map<String, String> map = new HashMap<>(8);
        Map<String, String> map = new ConcurrentHashMap<>(8);

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    map.put(UUID.randomUUID().toString().substring(0, 8), "");
                    System.out.println(Thread.currentThread().getName() + " \t" + map);
                }
            }, String.valueOf(i)).start();
        }
    }

    private static void setNotSafe() {
//        Set<String> set = new HashSet<>();
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i <= 30; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    set.add(UUID.randomUUID().toString().substring(0, 8));
                    System.out.println(Thread.currentThread().getName() + "\t" + set);
                }
            }, String.valueOf(i)).start();
        }
    }

    private static void listNotSafe() {
//        List<String> list = new ArrayList<>();
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    list.add(UUID.randomUUID().toString().substring(0, 8));
                    System.out.println(Thread.currentThread().getName() + "\t" + list);
                }
            }, String.valueOf(i)).start();


        }
    }
}
